<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useCloseContract, useGetAgreementCategoryOptions, useGetContractPage, useGetContractStatusOptions } from '@fl/api/supplier'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import { CONTRACT_STATUS, CONTRACT_STATUS_OPTIONS } from './constant'

defineOptions({
    name: window.location.href.includes('supplier-pages')
        ? '/supplier-pages/order-management/contract-management'
        : '/purchase-pages/purchase-order-management/contract-management',
})

const router = useRouter()
const route = useRoute()
const { createConfirmModal } = useMessage()

const initialState = {} as any
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const isSupplier = computed(() => route.path.includes('supplier-pages'))
const getContractPageParams = computed(() => ({
    ...searchConditions.value,
    page: tablePage.currentPage,
    size: tablePage.pageSize,
    type: isSupplier.value ? 1 : 0,
}))

const { data: contractStatusOptionsData } = useGetContractStatusOptions()
const { data: agreementCategoryOptionsData } = useGetAgreementCategoryOptions()
const { data: contractPageData, isLoading: isGetContractPageLoading, total: contractTotal } = useGetContractPage(getContractPageParams)
const { isPending: isCloseContractPending, mutate: closeContract } = useCloseContract()

// #region Form
const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '合同编号',
        prop: 'agreementCode',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '合同名称',
        prop: 'agreementName',
        valueType: 'copy',
    },
    // {
    //     colProps: {
    //         span: 6,
    //     },
    //     label: '协议类目',
    //     options: agreementCategoryOptionsData as OptionsType,
    //     prop: 'categoryId',
    //     valueType: 'select',
    // },
    {
        colProps: {
            span: 6,
        },
        label: '合同状态',
        options: contractStatusOptionsData as OptionsType,
        prop: 'contractStatus',
        valueType: 'select',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const isTableLoading = computed(() => isGetContractPageLoading.value)

const gridOptions = computed<VxeGridProps>(() => ({
    columns: [
        { field: 'agreementCode', title: '合同编号', width: 170 },
        { field: 'agreementName', slots: { default: 'agreement_name' }, title: '合同名称', width: 200 },
        { field: 'partyA', title: '甲方名称' },
        // { field: 'categoryName', title: '协议类目' },
        { field: 'contractPrice', title: '合同总价（元）' },
        { field: isSupplier.value ? 'totalAmountReceived' : 'totalAmountPaid', title: isSupplier.value ? '已收总金额（元）' : '已付总金额（元）' },
        { field: isSupplier.value ? 'remainingAmountDue' : 'remainingUnpaid', title: isSupplier.value ? '待收总金额（元）' : '待付总金额（元）' },
        { field: isSupplier.value ? 'totalAmountInvoiced' : 'totalInvoiceReceived', title: isSupplier.value ? '开票金额（元）' : '收票金额（元）' },
        { field: 'contractStatus', formatter: formatContractStatus, title: '状态' },
        { slots: { default: 'operation' }, title: '操作', width: 170 },
    ],
}))

function formatContractStatus({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: CONTRACT_STATUS_OPTIONS })
}

watchEffect(() => {
    tablePage.total = contractTotal.value
})
// #endregion

// #region UI Listener
function onCheckDetailBtnClick(row: any) {
    router.push({
        path: isSupplier.value
            ? '/supplier-pages/order-management/contract-detail'
            : '/purchase-pages/purchase-order-management/contract-detail',
        query: {
            id: row.agreementId,
        },
    })
}

function onCloseBtnClick(row: any) {
    createConfirmModal({
        content: '确定要关闭合同吗？',
        onSuccess: () => {
            closeContract(row.agreementId, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onAgreementNameClick(row: any) {
    onCheckDetailBtnClick(row)
}
// #endregion
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="contractPageData"
        >
            <template #operation="{ row }">
                <el-button text
                           type="primary"
                           class="!p-4"
                           @click="onCheckDetailBtnClick(row)"
                >
                    查看
                </el-button>

                <el-button v-if="!isSupplier && row.contractStatus !== CONTRACT_STATUS.COMPLETED"
                           text
                           type="primary"
                           class="!p-4"
                           :loading="isCloseContractPending"
                           @click="onCloseBtnClick(row)"
                >
                    关闭
                </el-button>
            </template>

            <template #agreement_name="{ row }">
                <span class="text-#409EFF truncate cursor-pointer"
                      @click="onAgreementNameClick(row)"
                >
                    {{ row.agreementName }}
                </span>
            </template>
        </SearchTable>
    </el-card>
</template>
